<template>
  <div class="balance">
    <mt-header title="发布">
      <router-link to="/user-haowu" slot="left">
        <mt-button icon="back"></mt-button>
      </router-link>
    </mt-header>
    <div class="haowu-list">
      <mt-field class="border-bottom" label="商品名称" placeholder="请输入商品名称" v-model="pro.name"></mt-field>
      <mt-field class="border-bottom" label="联系人" placeholder="请输入联系人" v-model="pro.contacts"></mt-field>
      <mt-field class="border-bottom" label="联系电话" placeholder="请输入联系电话" type="tel" v-model="pro.phone"></mt-field>
      <mt-field class="border-bottom" label="商品成色" placeholder="请输入商品成色" v-model="pro.condition"></mt-field>
      <mt-field class="border-bottom" label="商品原价" placeholder="请输入商品原价" v-model="pro.oldPrice"></mt-field>
      <mt-field class="border-bottom" label="商品现价" placeholder="请输入商品现价" v-model="pro.price"></mt-field>
      <mt-field class="border-bottom" label="商品数量" placeholder="请输入商品数量" type="number" v-model="pro.stock"></mt-field>
      <div @click="clickPicker">
        <mt-field class="border-bottom" label="所在区域" readonly :placeholder="myAddressProvince + '-' + myAddressCity + '-' + myAddresscounty"></mt-field>
      </div>
      <mt-field class="border-bottom" label="详细地址" placeholder="请输入详细地址" v-model="pro.address"></mt-field>
      <mt-field class="border-bottom" label="介绍" placeholder="介绍商品" type="textarea" rows="4" v-model="pro.introduce"></mt-field>
      <div>
        <div class="mint-cell-wrapper" style="background: #fff;padding-bottom: .3rem">
          <div class="mint-cell-title"><!----><span class="mint-cell-text">商品图片</span><!----></div>
        </div>
        <div class="spBottom">
          <div class="upimg">
            <img class="sptopImg1" v-show="pro.imgs1" :src="pro.imgs1">
            <img class="sptopImg2" v-show="!pro.imgs1" src="static/img/upfile.png">
            <input
              class="upimg-item"
              type="file"
              name="img1"
              id=""
              accept="image/gif,image/jpeg,image/jpg,image/png"
              @change="changeImage($event,'img1')"
              ref="license"
            >
          </div>
          <div class="upimg">
            <img class="sptopImg1" v-show="pro.imgs2" :src="pro.imgs2">
            <img class="sptopImg2" v-show="!pro.imgs2" src="static/img/upfile.png">
            <input
            class="upimg-item"
            type="file"
            name="img2"
            id=""
            accept="image/gif,image/jpeg,image/jpg,image/png"
            @change="changeImage($event,'img2')"
            ref="openingPermit">
          </div>
          <div class="upimg">
            <img class="sptopImg1" v-show="pro.imgs3" :src="pro.imgs3">
            <img class="sptopImg2" v-show="!pro.imgs3" src="static/img/upfile.png">
            <input
            class="upimg-item"
            type="file"
            name="img3"
            id=""
            accept="image/gif,image/jpeg,image/jpg,image/png"
            @change="changeImage($event,'img3')"
            ref="openingPermit">
          </div>
        </div>
      </div>
      <div @click="clickPicker" class="ispicker" v-show="isPicker">
        <mt-picker :slots="myAddressSlots" @change="onValuesChange"></mt-picker>
      </div>
    </div>
    <mt-button class="haowuBtn" @click="clickHandleBtn" size="large" type="danger">保存</mt-button>
  </div>
</template>

<script>
import { Toast } from 'mint-ui'
import axios from 'axios'
import myaddress from '../../../static/json/area.json'
export default {
  name: 'HaowuAdd',
  data () {
    return {
      isPicker: false,
      pro: {
        name: '',
        contacts: '',
        address: '',
        areaId: '',
        oldPrice: '',
        price: '',
        stock: 1,
        condition: '',
        introduce: '',
        imgs1: '',
        imgs2: '',
        imgs3: '',
        phone: ''
      },
      myAddressSlots: [
        {
          flex: 1,
          defaultIndex: 1,
          values: Object.keys(myaddress),
          className: 'slot1',
          textAlign: 'center'
        }, {
          divider: true,
          content: '-',
          className: 'slot2'
        }, {
          flex: 1,
          values: [],
          className: 'slot3',
          textAlign: 'center'
        }, {
          divider: true,
          content: '-',
          className: 'slot4'
        }, {
          flex: 1,
          values: [],
          className: 'slot5',
          textAlign: 'center'
        }
      ],
      myAddressProvince: '省',
      myAddressCity: '市',
      myAddresscounty: '区/县'
    }
  },
  methods: {
    clickHandleBtn () {
      var params = new URLSearchParams()
      params.append('memberId', this.$store.state.userId)
      if (this.pro.name.length < 1) {
        Toast('请输入商品名称')
        return null
      }
      params.append('name', this.pro.name)
      if (this.pro.contacts.length < 1) {
        Toast('请输入联系人')
        return null
      }
      params.append('contacts', this.pro.contacts)
      if (this.pro.phone.length < 1) {
        Toast('请输入联系电话')
        return null
      }
      params.append('phone', this.pro.phone)
      if (this.pro.condition.length < 1) {
        Toast('请输入商品成色')
        return null
      }
      params.append('condition', this.pro.condition)
      if (this.pro.oldPrice.length < 1) {
        Toast('请输入商品原价')
        return null
      }
      params.append('oldPrice', this.pro.oldPrice)
      if (this.pro.price.length < 1) {
        Toast('请输入商品现价')
        return null
      }
      params.append('price', this.pro.price)
      if (this.pro.stock.length < 1) {
        Toast('请输入商品数量')
        return null
      }
      params.append('stock', this.pro.stock)
      if (this.pro.address.length < 1) {
        Toast('详细地址')
        return null
      }
      params.append('address', this.pro.address)
      if (this.pro.introduce) {
        params.append('introduce', this.pro.introduce)
      }
      params.append('areaFullName', this.myAddressProvince + this.myAddressCity + this.myAddresscounty)
      let titleImg = ''
      let titleImgList = []
      if (this.pro.imgs1) {
        titleImg = this.pro.imgs1
      } else if (this.pro.imgs2) {
        titleImg = this.pro.imgs2
      } else if (this.pro.imgs3) {
        titleImg = this.pro.imgs3
      }
      if (!titleImg) {
        Toast('请上传商品图片')
        return null
      }
      params.append('titleImg', titleImg)
      if (this.pro.imgs1) {
        params.append('img1', this.pro.imgs1)
        console.log('img1')
      }
      if (this.pro.imgs2) {
        params.append('img2', this.pro.imgs2)
        console.log('img2')
      }
      if (this.pro.imgs3) {
        params.append('img3', this.pro.imgs3)
        console.log('img3')
      }
      axios.post('/meimai/interface/goodsUsed/save', params).then((res) => {
        console.log(res)
        let datas = res.data
        if (datas.code === 0) {
          Toast('发布成功')
          this.$router.push('/user-haowu')
        }
      })
      console.log(titleImgList)
      // console.log(titleImg)
    },
    onValuesChange (picker, values) {
      if (myaddress[values[0]]) {
        picker.setSlotValues(1, Object.keys(myaddress[values[0]]))
        picker.setSlotValues(2, myaddress[values[0]][values[1]])
        this.myAddressProvince = values[0]
        // this.myAddressCity = values[1]
        if (values[1]) {
          this.myAddressCity = values[1]
        } else {
          this.myAddressCity = '其他'
        }
        if (values[2]) {
          this.myAddresscounty = values[2]
        } else {
          this.myAddresscounty = '其他'
        }
      }
    },
    clickPicker () {
      this.isPicker = !this.isPicker
    },
    photoCompress (file, obj, callback) {
      let that = this
      let ready = new FileReader()
      // 开始读取指定File对象中的内容. 读取操作完成时,返回一个URL格式的字符串.
      ready.readAsDataURL(file)
      ready.onload = function () {
        let re = this.result
        that.canvasDataURL(re, obj, callback) // 开始压缩
      }
    },
    canvasDataURL (path, obj, callback) {
      let img = new Image()
      img.src = path
      img.onload = function () {
        let that = this // 指到img
        // 默认按比例压缩
        let w = that.width
        let h = that.height
        let scale = w / h
        w = obj.width || w
        h = obj.height || (w / scale)
        let quality = 0.7 // 默认图片质量为0.7
        // 生成canvas
        let canvas = document.createElement('canvas')
        let ctx = canvas.getContext('2d')
        // 创建属性节点
        let anw = document.createAttribute('width')
        anw.nodeValue = w
        let anh = document.createAttribute('height')
        anh.nodeValue = h
        canvas.setAttributeNode(anw)
        canvas.setAttributeNode(anh)
        ctx.drawImage(that, 0, 0, w, h)
        // 图像质量
        if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
          quality = obj.quality
        }
        // quality值越小，所绘制出的图像越模糊
        let base64 = canvas.toDataURL('image/jpeg', quality)
        // 回调函数返回base64的值
        callback(base64)
      }
    },
    base64UrlToBlob (urlData) {
      let arr = urlData.split(',')
      let mime = arr[0].match(/:(.*?);/)[1] // 去掉url的头，并转化为byte
      let bstr = atob(arr[1]) // 处理异常,将ascii码小于0的转换为大于0
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
      // 转file
      // return new File([u8arr], filename, {type:mime});
    },
    changeImage (e, data) {
      let that = this
      let file = e.target.files[0]
      var reader = new FileReader()
      // var img = new Image()
      if (file.type.indexOf('image') === 0) {
        reader.readAsDataURL(file)
      }
      if (file.size / 1024 > 1025) {
        that.photoCompress(file, { // 调用压缩图片方法
          quality: 0.2
        }, function (base64Codes) {
          // console.log('压缩后：' + base.length / 1024 + ' ' + base)
          let bl = that.base64UrlToBlob(base64Codes)
          // console.log(base64Codes)
          console.log(bl)
          if (data === 'img1') {
            that.pro.imgs1 = base64Codes
          }
          if (data === 'img2') {
            that.pro.imgs2 = base64Codes
          }
          if (data === 'img3') {
            that.pro.imgs3 = base64Codes
          }
        })
      } else { // 小于等于1M 原图上传
        reader.onload = function (e) {
          if (data === 'img1') {
            that.pro.imgs1 = this.result
          }
          if (data === 'img2') {
            that.pro.imgs2 = this.result
          }
          if (data === 'img3') {
            that.pro.imgs3 = this.result
          }
        }
      }
    }
  },
  mounted () {
    if (this.$route.query.addressId) {
      this.getInfo()
    }
    this.$nextTick(() => {
      this.myAddressSlots[0].defaultIndex = 0
    })
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/mixins.styl'
@import '~styles/varibles.styl'
.mint-header
  background: $colorRed
.ispicker
  background: rgba(0, 0, 0, .7)
  position: absolute
  top: 0
  width: 100%
  bottom: 0
  z-index: 1
  .picker
    background: #fff
    margin-top: 50%
.haowu-list
  margin-bottom: .3rem
.spBottom
  width: 100%
  display: flex
  justify-content: space-around
  padding-bottom: .3rem
  background: #fff
  .upimg
    background-color: #f3f3f3
    width: 2.2rem
    height: 1.5rem
    display: flex
    align-items: center
    justify-content: center
    overflow: hidden
    position: relative
    .sptopImg1
      width: 100%
      height: 100%
    .sptopImg2
      height: .5rem
      width: .5rem
    .upimg-item
      position: absolute
      top: 0
      left: 0
      opacity: 0
      width: 100%
      height: 100%
      z-index: 999
.haowuBtn
  box-sizing: border-box
.redColor
  color: red
</style>
